3.1 Basic Configuration
3.1.1 Built in options
3.1.2 Logging
3.1.3 GORM
3.2 Environments
3.3 The DataSource
3.3.1 DataSources and Environments
3.3.2 JNDI DataSources
3.3.3 Automatic Database Migration
3.4 Externalized Configuration
3.5 Versioning
3.6 Project Documentation
3.7 Dependency Resolution
3.7.1 Configurations and Dependencies
3.7.2 Dependency Repositories
3.7.3 Debugging Resolution
3.7.4 Inherited Dependencies
3.7.5 Providing Default Dependencies
3.7.6 Dependency Reports
3.7.7 Plugin JAR Dependencies
3.7.8 Maven Integration
It may seem odd that in a framework that embraces "convention-over-configuration" that we tackle this topic now, but since what configuration there is typically a one off, it is best to get it out the way.

With Grails' default settings you can actually develop and application without doing any configuration whatsoever. Grails ships with an embedded container and in-memory HSQLDB meaning there isn't even a database to set-up.

However, typically you want to set-up a real database at some point and the way you do that is described in the following section.

3.1 Basic Configuration

For general configuration Grails provides a file called grails-app/conf/Config.groovy. This file uses Groovy's ConfigSlurper which is very similar to Java properties files except it is pure Groovy hence you can re-use variables and use proper Java types!

You can add your own configuration in here, for example:

foo.bar.hello = "world"

Then later in your application you can access these settings in one of two ways. The most common is via the GrailsApplication object, which is available as a variable in controllers and tag libraries:

assert "world" == grailsApplication.config.foo.bar.hello

The other way involves getting a reference to the ConfigurationHolder class that holds a reference to the configuration object:

import org.codehaus.groovy.grails.commons.*
…
def config = ConfigurationHolder.config
assert "world" == config.foo.bar.hello

3.1.1 Built in options

Grails also provides the following configuration options:

War generation

For more information on using these options, see the section on deployment

3.1.2 Logging

Logging Basics

Grails uses its common configuration mechanism to configure the underlying Log4j log system. To configure logging you must modify the file Config.groovy located in the grails-app/conf directory.

This single Config.groovy file allows you to specify separate logging configurations for development, test, and production environments. Grails processes the Config.groovy and configures Log4j appropriately.

Since 1.1 Grails provides a Log4j DSL, that you can use to configure Log4j an example of which can be seen below:

log4j = {
    error  'org.codehaus.groovy.grails.web.servlet',  //  controllers
	       'org.codehaus.groovy.grails.web.pages' //  GSP

warn 'org.mortbay.log' }

Essentially, each method translates into a log level and you can pass the names of the packages you want to log at that level as arguments to the method.

Some useful loggers include:

The Root Logger

The Root logger is the logger that all other loggers inherit from. You can configure the Root logger using the root method:

root {
    error()
    additivity = true
}

The above example configures the root logger to log messages at the error level and above to the default standard out appender. You can also configure the root logger to log to one or more named appenders:

appenders {
	file name:'file', file:'/var/logs/mylog.log'
}
root {
    debug 'stdout', 'file'
    additivity = true
}

Here the root logger will log to two appenders - the default 'stdout' appender and a 'file' appender.

You can also configure the root logger from the argument passed into the Log4J closure:

log4j = { root ->
    root.level = org.apache.log4j.Level.DEBUG
    …
}
The closure argument "root" is an instance of org.apache.log4j.Logger , so refer to the API documentation for Log4J to find out what properties and methods are available to you.

Custom Appenders

Using the Log4j you can define custom appenders. The following appenders are available by default:

For example to configure a rolling file appender you can do:

log4j = {
	appenders {
		rollingFile name:"myAppender", maxFileSize:1024, file:"/tmp/logs/myApp.log"
	}
}

Each argument passed to the appender maps to a property of underlying Appender class. The example above sets the name, maxFileSize and file properties of the RollingFileAppender class.

If you prefer to simply create the appender programmatically yourself, or you have your own appender implementation then you can simply call the appender method and appender instance:

import org.apache.log4j.*

log4j = { appenders { appender new RollingFileAppender(name:"myAppender", maxFileSize:1024, file:"/tmp/logs/myApp.log") } }

You can then log to a particular appender by passing the name as a key to one of the log level methods from the previous section:

error myAppender:"org.codehaus.groovy.grails.commons"

Custom Layouts

By default the Log4j DSL assumes that you want to use a PatternLayout. However, there are other layouts available including:

You can specify custom patterns to an appender using the layout setting:

log4j = {
	appenders {
        console name:'customAppender', layout:pattern(conversionPattern: '%c{2} %m%n')
    }
}

This also works for the built-in appender "stdout", which logs to the console:

log4j = {
    appenders {
        console name:'stdout', layout:pattern(conversionPattern: '%c{2} %m%n')
    }
}

Full stacktraces

When exceptions occur, there can be an awful lot of noise in the stacktrace from Java and Groovy internals. Grails filters these typically irrelevant details and restricts traces to non-core Grails/Groovy class packages.

When this happens, the full trace is always written to the StackTrace logger. This logs to a file called stacktrace.log - but you can change this in your Config.groovy to do anything you like. For example if you prefer full stack traces to go to standard out you can add this line:

error stdout:"StackTrace"

You can completely disable stacktrace filtering by setting the grails.full.stacktrace VM property to true:

grails -Dgrails.full.stacktrace=true run-app

Logging by Convention

All application artefacts have a dynamically added log property. This includes domain classes, controllers, tag libraries and so on. Below is an example of its usage:

def foo = "bar"
log.debug "The value of foo is $foo"

Logs are named using the convention grails.app.<artefactType>.ClassName. Below is an example of how to configure logs for different Grails artefacts:

log4j = {
	// Set level for all application artefacts
	info "grails.app"
	// Set for a specific controller
	debug "grails.app.controller.YourController"
	// Set for a specific domain class
	debug "grails.app.domain.Book"
	// Set for all taglibs
	info "grails.app.tagLib"

}

The artefacts names are dictated by convention, some of the common ones are listed below:

3.1.3 GORM

Grails provides the following GORM configuration options:

Enable failOnError for all domain classes…

grails.gorm.failOnError=true

Enable failOnError for domain classes by package…

grails.gorm.failOnError = ['com.companyname.somepackage', 'com.companyname.someotherpackage']

3.2 Environments

Per Environment Configuration

Grails supports the concept of per environment configuration. Both the Config.groovy file and the DataSource.groovy file within the grails-app/conf directory can take advantage of per environment configuration using the syntax provided by ConfigSlurper As an example consider the following default DataSource definition provided by Grails:

dataSource {
    pooled = false                          
    driverClassName = "org.hsqldb.jdbcDriver"	
    username = "sa"
    password = ""				
}
environments {
    development {
        dataSource {
            dbCreate = "create-drop" // one of 'create', 'createeate-drop','update'
            url = "jdbc:hsqldb:mem:devDB"
        }
    }   
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:hsqldb:mem:testDb"
        }
    }   
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:hsqldb:file:prodDb;shutdown=true"
        }
    }
}

Notice how the common configuration is provided at the top level and then an environments block specifies per environment settings for the dbCreate and url properties of the DataSource. This syntax can also be used within Config.groovy.

Packaging and Running for Different Environments

Grails' command line has built in capabilities to execute any command within the context of a specific environment. The format is:

grails [environment] [command name]

In addition, there are 3 preset environments known to Grails: dev, prod, and test for development, production and test. For example to create a WAR for the test environment you could do:

grails test war

If you have other environments that you need to target you can pass a grails.env variable to any command:

grails -Dgrails.env=UAT run-app

Programmatic Environment Detection

Within your code, such as in a Gant script or a bootstrap class you can detect the environment using the Environment class:

import grails.util.Environment

...

switch(Environment.current) { case Environment.DEVELOPMENT: configureForDevelopment() break case Environment.PRODUCTION: configureForProduction() break }

Per Environment Bootstrapping

Its often desirable to run code when your application starts up on a per-environment basis. To do so you can use the grails-app/conf/BootStrap.groovy file's support for per-environment execution:

def init = { ServletContext ctx ->
        environments {
            production {
                ctx.setAttribute("env", "prod")
            }
            development {
                ctx.setAttribute("env", "dev")
            }
        }
        ctx.setAttribute("foo", "bar")
}

Generic Per Environment Execution

The previous BootStrap example uses the grails.util.Environment class internally to execute. You can also use this class yourself to execute your own environment specific logic:

Environment.executeForCurrentEnvironment {
	production {
		// do something in production
	}
	development {
		// do something only in development
	}
}

3.3 The DataSource

Since Grails is built on Java technology to set-up a data source requires some knowledge of JDBC (the technology that doesn't stand for Java Database Connectivity).

Essentially, if you are using another database other than HSQLDB you need to have a JDBC driver. For example for MySQL you would need Connector/J

Drivers typically come in the form of a JAR archive. Drop the JAR into your projects lib directory.

Once you have the JAR in place you need to get familiar Grails' DataSource descriptor file located at grails-app/conf/DataSource.groovy. This file contains the dataSource definition which includes the following settings:

A typical configuration for MySQL may be something like:

dataSource {
	pooled = true
	dbCreate = "update"
	url = "jdbc:mysql://localhost/yourDB"
	driverClassName = "com.mysql.jdbc.Driver"
	username = "yourUser"
	password = "yourPassword"	
}

When configuring the DataSource do not include the type or the def keyword before any of the configuration settings as Groovy will treat these as local variable definitions and they will not be processed. For example the following is invalid:

dataSource {
	boolean pooled = true // type declaration results in local variable
	…
}

Example of advanced configuration using extra properties:

dataSource {
	pooled = true
	dbCreate = "update"
	url = "jdbc:mysql://localhost/yourDB"
	driverClassName = "com.mysql.jdbc.Driver"
	username = "yourUser"
	password = "yourPassword"
	properties {
		maxActive = 50
		maxIdle = 25
		minIdle = 5
		initialSize = 5
		minEvictableIdleTimeMillis = 60000
		timeBetweenEvictionRunsMillis = 60000
		maxWait = 10000		
	}	
}

3.3.1 DataSources and Environments

The previous example configuration assumes you want the same config for all environments: production, test, development etc.

Grails' DataSource definition is "environment aware", however, so you can do:

dataSource {
	// common settings here
}                     
environments {
  production {
     dataSource {
          url = "jdbc:mysql://liveip.com/liveDb"					
     }			
  }
}

3.3.2 JNDI DataSources

Since many Java EE containers typically supply DataSource instances via the Java Naming and Directory Interface (JNDI). Sometimes you are required to look-up a DataSource via JNDI.

Grails supports the definition of JNDI data sources as follows:

dataSource {
    jndiName = "java:comp/env/myDataSource"
}

The format on the JNDI name may vary from container to container, but the way you define the DataSource remains the same.

3.3.3 Automatic Database Migration

The dbCreate property of the DataSource definition is important as it dictates what Grails should do at runtime with regards to automatically generating the database tables from GORM classes. The options are:

Both create-drop and create will destroy all existing data hence use with caution!

In development mode dbCreate is by default set to "create-drop":

dataSource {
	dbCreate = "create-drop" // one of 'create', 'create-drop','update'
}

What this does is automatically drop and re-create the database tables on each restart of the application. Obviously this may not be what you want in production.

Although Grails does not currently support Rails-style Migrations out of the box, there are currently three plugins that provide similar capabilities to Grails: Autobase (http://wiki.github.com/RobertFischer/autobase), The LiquiBase plugin and the DbMigrate plugin both of which are available via the grails list-plugins command

3.4 Externalized Configuration

The default configuration file Config.groovy in grails-app/conf is fine in the majority of cases, but there may be circumstances where you want to maintain the configuration in a file outside the main application structure. For example if you are deploying to a WAR some administrators prefer the configuration of the application to be externalized to avoid having to re-package the WAR due to a change of configuration.

In order to support deployment scenarios such as these the configuration can be externalized. To do so you need to point Grails at the locations of the configuration files Grails should be using by adding a grails.config.locations setting in Config.groovy:

grails.config.locations = [ "classpath:${appName}-config.properties",
                            "classpath:${appName}-config.groovy",
                            "file:${userHome}/.grails/${appName}-config.properties",
                            "file:${userHome}/.grails/${appName}-config.groovy"]

In the above example we're loading configuration files (both Java properties files and ConfigSlurper configurations) from different places on the classpath and files located in USER_HOME.

Ultimately all configuration files get merged into the config property of the GrailsApplication object and are hence obtainable from there.

Grails also supports the concept of property place holders and property override configurers as defined in Spring For more information on these see the section on Grails and Spring

3.5 Versioning

Versioning Basics

Grails has built in support for application versioning. When you first create an application with the create-app command the version of the application is set to 0.1. The version is stored in the application meta data file called application.properties in the root of the project.

To change the version of your application you can run the set-version command:

grails set-version 0.2

The version is used in various commands including the war command which will append the application version to the end of the created WAR file.

Detecting Versions at Runtime

You can detect the application version using Grails' support for application metadata using the GrailsApplication class. For example within controllers there is an implicit grailsApplication variable that can be used:

def version = grailsApplication.metadata['app.version']

If it is the version of Grails you need you can use:

def grailsVersion = grailsApplication.metadata['app.grails.version']

or the GrailsUtil class:

import grails.util.*
def grailsVersion = GrailsUtil.grailsVersion

3.6 Project Documentation

Since Grails 1.2, the documentation engine that powers the creation of this documentation is available to your Grails projects.

The documentation engine uses a variation on the Textile syntax to automatically create project documentation with smart linking, formatting etc.

Creating project documentation

To use the engine you need to follow a few conventions. Firstly you need to create a src/docs/guide directory and then have numbered text files using the gdoc format. For example:

+ src/docs/guide/1. Introduction.gdoc
+ src/docs/guide/2. Getting Started.gdoc

The title of each chapter is taken from the file name. The order is dictated by the numerical value at the beginning of the file name.

Creating reference items

Reference items appear in the left menu on the documentation and are useful for quick reference documentation. Each reference item belongs to a category and a category is a directory located in the src/docs/ref directory. For example say you defined a new method called renderPDF, that belongs to a category called Controllers this can be done by creating a gdoc text file at the following location:

+ src/ref/Controllers/renderPDF.gdoc

Configuring Output Properties

There are various properties you can set within your grails-app/conf/Config.groovy file that customize the output of the documentation such as:

Other properties such as the name of the documentation and the version are pulled from your project itself.

Generating Documentation

Once you have created some documentation (refer to the syntax guide in the next chapter) you can generate an HTML version of the documentation using the command:

grails docs

This command will output an docs/manual/index.html which can be opened to view your documentation.

Documentation Syntax

As mentioned the syntax is largely similar to Textile or Confluence style wiki markup. The following sections walk you through the syntax basics.

Basic Formatting

Monospace: monospace

@monospace@

Italic: italic

_italic_

Bold: bold

*bold*

Image:

!http://grails.org/images/new/grailslogo_topNav.png!

Linking

There are several ways to create links with the documentation generator. A basic external link can either be defined using confluence or textile style markup:

[SpringSource|http://www.springsource.com/] or "SpringSource":http://www.springsource.com/

For links to other sections inside the user guide you can use the guide: prefix:

[Intro|guide:1. Introduction]

The documentation engine will warn you if any links to sections in your guide break. Sometimes though it is preferable not to hard code the actual names of guide sections since you may move them around. To get around this you can create an alias inside grails-app/conf/Config.groovy:

grails.doc.alias.intro="1. Introduction"

And then the link becomes:

[Intro|guide:intro]

This is useful since if you linked the to "1. Introduction" chapter many times you would have to change all of those links.

To link to reference items you can use a special syntax:

[controllers|renderPDF]

In this case the category of the reference item is on the left hand side of the | and the name of the reference item on the right.

Finally, to link to external APIs you can use the api: prefix. For example:

[String|api:java.lang.String]

The documentation engine will automatically create the appropriate javadoc link in this case. If you want to add additional APIs to the engine you can configure them in grails-app/conf/Config.groovy. For example:

grails.doc.api.org.hibernate="http://docs.jboss.org/hibernate/stable/core/api"

The above example configures classes within the org.hibernate package to link to the Hibernate website's API docs.

Lists and Headings

Headings can be created by specifying the letter 'h' followed by a number and then a dot:

h3.<space>Heading3
h4.<space>Heading4

Unordered lists are defined with the use of the * character:

* item 1
** subitem 1
** subitem 2
* item 2

Numbered lists can be defined with the # character:

# item 1

Tables can be created using the table macro:

NameNumber
Albert46
Wilma1348
James12

{table}
 *Name* | *Number* 
 Albert | 46
 Wilma | 1348
 James | 12
{table}

Code and Notes

You can define code blocks with the code macro:

class Book {
    String title
}

{code}
class Book {
    String title
}
{code}

The example above provides syntax highlighting for Java and Groovy code, but you can also highlight XML markup:

<hello>world</hello>

{code:xml}
<hello>world</hello>
{code}

There are also a couple of macros for displaying notes and warnings:

Note:

This is a note!

{note}
This is a note!
{note}

Warning:

This is a warning!

{warning}
This is a warning!
{warning}

3.7 Dependency Resolution

In order to control how JAR dependencies are resolved Grails features (since version 1.2) a dependency resolution DSL that allows you to control how dependencies for applications and plugins are resolved.

Inside the grails-app/conf/BuildConfig.groovy file you can specify a grails.project.dependency.resolution property that configures how dependencies are resolved:

grails.project.dependency.resolution = {
   // config here
}

The default configuration looks like the following:

grails.project.dependency.resolution = {
    inherits "global" // inherit Grails' default dependencies
    log "warn" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
    repositories {
        grailsHome()

// uncomment the below to enable remote dependency resolution // from public Maven repositories //mavenCentral() //mavenRepo "http://snapshots.repository.codehaus.org" //mavenRepo "http://repository.codehaus.org" //mavenRepo "http://download.java.net/maven/2/" //mavenRepo "http://repository.jboss.com/maven2/ } dependencies { // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg. // runtime 'com.mysql:mysql-connector-java:5.1.5' }

}

The details of the above will be explained in the next few sections.

3.7.1 Configurations and Dependencies

Grails features 5 dependency resolution configurations (or 'scopes') which you can take advantage of:

Within the dependencies block you can specify a dependency that falls into one of these configurations by calling the equivalent method. For example if your application requires the MySQL driver to function at runtime you can specify as such:

runtime 'com.mysql:mysql-connector-java:5.1.5'

The above uses the string syntax which is group:name:version. You can also use a map-based syntax:

runtime group:'com.mysql', name:'mysql-connector-java', version:'5.1.5'

Multiple dependencies can be specified by passing multiple arguments:

runtime 'com.mysql:mysql-connector-java:5.1.5',
		'net.sf.ehcache:ehcache:1.6.1'

// Or

runtime( [group:'com.mysql', name:'mysql-connector-java', version:'5.1.5'], [group:'net.sf.ehcache', name:'ehcache', version:'1.6.1'] )

3.7.2 Dependency Repositories

Remote Repositories

Grails, when installed, does not use any remote public repositories. There is a default grailsHome() repository that will locate the JAR files Grails needs from your Grails installation. If you want to take advantage of a public repository you need to specify as such inside the repositories block:

repositories {
    mavenCentral()
}

In this case the default public Maven repository is specified. To use the SpringSource Enterprise Bundle Repository you can use the ebr() method:

repositories {
    ebr()
}

You can also specify a specific Maven repository to use by URL:

repositories {
	mavenRepo "http://repository.codehaus.org"
}

Local Resolvers

If you do not wish to use a public Maven repository you can specify a flat file repository:

repositories {
	flatDir name:'myRepo', dirs:'/path/to/repo'
}

Custom Resolvers

If all else fails since Grails builds on Apache Ivy you can specify an Ivy resolver:

repositories {
	resolver new URLResolver(...)
}

Authentication

If your repository requires some form of authentication you can specify as such using a credentials block:

credentials {
	realm = ".."
	host = "localhost"
	username = "myuser"
	password = "mypass"
}

The above can also be placed in your USER_HOME/.grails/settings.groovy file using the grails.project.ivy.authentication setting:

grails.project.ivy.authentication = {
	credentials {
		realm = ".."
		host = "localhost"
		username = "myuser"
		password = "mypass"
	}	
}

3.7.3 Debugging Resolution

If you are having trouble getting a dependency to resolve you can enable more verbose debugging from the underlying engine using the log method:

// log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
log "warn"

3.7.4 Inherited Dependencies

By default every Grails application inherits a bunch of framework dependencies. This is done through the line:

inherits "global"

Inside the BuildConfig.groovy file. If you wish exclude certain inherited dependencies then you can do so using the excludes method:

inherits("global") {
	excludes "oscache", "ehcache"
}

3.7.5 Providing Default Dependencies

Most Grails applications will have runtime dependencies on a lot of jar files that are provided by the Grails framework. These include libraries like Spring, Sitemesh, Hibernate etc. When a war file is created, all of these dependencies will be included in it. But, an application may choose to exclude these jar files from the war. This is useful when the jar files will be provided by the container, as would normally be the case if multiple Grails applications are deployed to the same container. The dependency resolution DSL provides a mechanism to express that all of the default dependencies will be provided by the container. This is done by invoking the defaultDependenciesProvided method and passing true as an argument:

grails.project.dependency.resolution = {

defaultDependenciesProvided true // all of the default dependencies will be "provided" by the container

inherits "global" // inherit Grails' default dependencies

repositories { grailsHome() // … } dependencies { // … } }

Note that defaultDependenciesProvided must come before inherits, otherwise the Grails dependencies will be included in the war.

3.7.6 Dependency Reports

As mentioned in the previous section a Grails application consists of dependencies inherited from the framework, the plugins installed and the application dependencies itself.

To obtain a report of an application's dependencies you can run the dependency-report command:

grails dependency-report

This will output a report to the target/dependency-report directory by default. You can specify which configuration (scope) you want a report for by passing an argument containing the configuration name:

grails dependency-report runtime

3.7.7 Plugin JAR Dependencies

Specifying Plugin JAR dependencies

The way in which you specify dependencies for a plugin is identical to how you specify dependencies in an application. When a plugin is installed into an application the application automatically inherits the dependencies of the plugin.

If you want to define a dependency that is resolved for use with the plugin but not exported to the application then you can set the exported property of the dependency:

compile( 'org.hibernate:hibernate-core:3.3.1.GA') {
	exported = false
}

In this can the hibernate-core dependency will be available only to the plugin and not resolved as an application dependency.

Overriding Plugin JAR Dependencies in Your Application

If a plugin is using a JAR which conflicts with another plugin, or an application dependency then you can override how a plugin resolves its dependencies inside an application using the plugin method:

plugin("hibernate") {
    compile( 'org.hibernate:hibernate-core:3.3.1.GA') {
		excludes 'ehcache', 'xml-apis', 'commons-logging'
	}
    compile 'org.hibernate:hibernate-annotations:3.4.0.GA',
			'org.hibernate:hibernate-commons-annotations:3.3.0.ga'

runtime 'javassist:javassist:3.4.GA' }

In this case the application is controlling how the hibernate plugin resolves dependencies and not the hibernate plugin. If you wish to simply exclude a single dependency resolved by a plugin then you can do so:

plugin("hibernate") {
    runtime "cglib:cglib-nodep:2.1_3"
	excludes 'javassist:javassist:3.4.GA'	
}

3.7.8 Maven Integration

When using the Grails Maven plugin, Grails' dependency resolution mechanics are disabled as it is assumed that you will manage dependencies via Maven's pom.xml file.

However, if you would like to continue using Grails regular commands like run-app, test-app and so on then you can tell Grails' command line to load dependencies from the Maven pom.xml file instead.

To do so simply add the following line to your BuildConfig.groovy:

grails.project.dependency.resolution = {
 	pom true
	..
}

The line pom true tells Grails to parse Maven's pom.xml and load dependencies from there.